package com.knight.hadoop.day10.preprocess;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.commons.lang.ArrayUtils;

/**
 * 
 * web日志的预处理解析器
 * 
 * @author
 *
 */
public class WebLogParser {
	
	private static SimpleDateFormat format1 = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss",Locale.US);
	private static SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 
	 * @param line
	 *            map读取到的数据
	 * @return
	 */
	public static WebLogObject parse(String line) {

		String[] values = line.split(" ");

		/*
		 * for (int i = 0; i < values.length; i++) { System.out.println(i + ": "
		 * + values[i]); }
		 */
			
		
		WebLogObject webLogObject = new WebLogObject();
		if (values.length >11) {

			String requestIP = values[0];// 194.237.142.21
			String requestDate = parseDate(values[3].substring(1));// [18/Sep/2013:06:49:18
			String requestMethod = values[5];// "GET
			String requestURL = values[6]; /// wp-content/uploads/2013/07/rstudio-git3.png
			String requestProtocol = values[7];// HTTP/1.0"
			String responseCode = values[8];// 200
			String responseDataSize = values[9];// 185524
			String requestSourcesURL = values[10];// "http://cos.name/category/software/packages/"
			Object[] subarray = ArrayUtils.subarray(values, 11, values.length);
			String customerInfo = ArrayUtils.toString(subarray);// {"Mozilla/5.0,(Windows,NT,6.1),AppleWebKit/537.36,(KHTML,,like,Gecko),Chrome/29.0.1547.66,Safari/537.36"}

			
			webLogObject.set(requestIP, requestDate, requestMethod, requestURL, requestProtocol, responseCode,
					responseDataSize, requestSourcesURL, customerInfo);
			if(Integer.parseInt(responseCode)>=400){
				webLogObject.setValid(false);
			}
			
		}else{
			webLogObject.setValid(false);
		}
		return webLogObject;
	}
	
	
	public static String parseDate(String date){
		Date parseDate = null;
		try {
			parseDate = format1.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return format2.format(parseDate);
	}
}
